<template>
  <div class="admin">
    <div class="opts">
      <div class="left">
        <input class="custinput" v-model="state.title" placeholder="输入文章标题..." maxlength="80" />
      </div>
      <div class="right">
        <el-button @click="goHome">返回文章列表</el-button>
        <el-button @click="onCancel" type="primary">{{ state.type === "update" ? "修改" : "发布" }}</el-button>
        <el-avatar
          style="margin-top: -10px"
          src="https://img2.baidu.com/it/u=2744676768,2143551610&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=502"
          :size="45"
        ></el-avatar>
      </div>
    </div>
    <Editor
      class="editos"
      :value="state.value"
      :plugins="plugins"
      :locale="zhHans"
      @change="handleChange"
      :upload-images="uploadImage"
    />
  </div>
  <template v-if="state.flag">
    <Popup :show="state.flag" :update-data="updateData" @on-cancel="onCancel" @on-success="sumbit" />
  </template>
</template>
<script setup lang="ts">
import "bytemd/dist/index.css";
import { Editor } from "@bytemd/vue-next";
import gfm from "@bytemd/plugin-gfm";
import highlight from "@bytemd/plugin-highlight";
import breaks from "@bytemd/plugin-breaks";
import footnotes from "@bytemd/plugin-footnotes";
import frontmatter from "@bytemd/plugin-frontmatter";
import gemoji from "@bytemd/plugin-gemoji";
import mediumZoom from "@bytemd/plugin-medium-zoom";
import zhHans from "bytemd/locales/zh_Hans.json";
// import "juejin-markdown-themes/dist/scrolls-light.css";
import "juejin-markdown-themes/dist/geek-black.min.css";
import { nextTick, onMounted, reactive, ref } from "vue";
// import { addBlog, getBlogDetails, updateBlog } from "@/api";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { addBlogApi, updateBlogApi, detailBlogApi } from "@/api/modules/article";
import axios from "axios";
import Popup from "@/components/Popup/index.vue";
import dayjs from "dayjs";
const plugins = [gfm(), highlight(), breaks(), frontmatter(), footnotes(), gemoji(), mediumZoom()];

const route = useRoute();
const router = useRouter();
const state = reactive({
  value: "",
  maxLength: 200,
  title: "",
  flag: false,
  type: "add",
  id: 0
});

const updateData = ref<any>({});

onMounted(() => {
  let id = route?.query?.id;
  // 开始更新的逻辑
  if (id && id !== "0") {
    updateInfo(+id);
    state.id = +id;
    state.type = "update";
  }

  // 隐藏右边目录
  // nextTick(() => {
  //   let rightMenu: any = document.querySelector(".bytemd-toolbar-right");
  //   console.log(rightMenu);
  //   rightMenu.style = "display: none;";
  // });
});

const handleChange = (val: any) => {
  // console.warn(val)
  state.value = val;
};

const uploadImage = async (files: any) => {
  console.log("files", files);
  const {
    data: { url }
  } = await sumbitImage(files[0]);
  console.warn("图片链接", url);
  return [
    {
      title: files.map((i: any) => i.name),
      url
    }
  ];
};

const sumbitImage = async (file: any) => {
  const data = new FormData();
  data.append("file", file);
  // 服务器图片接口地址，
  const result = await axios.post("", data, {
    headers: { "content-Type": "multipart/form-data" }
  });
  console.log(result);
  return result?.data;
};

// 这里去提交
const sumbit = async (item: any, type: any) => {
  let { title, value } = state;
  let { desc, cover, label } = JSON.parse(item);
  if (!title || !value) {
    ElMessage.warning("请填写标题和文章内容");
    return;
  }

  // 更新逻辑
  if (state.type === "update") {
    let items = JSON.parse(item);
    fixBlogDetail(items, type);
    return;
  }

  // 新增逻辑
  const { code } = await addBlogApi({
    title,
    desc,
    content: value,
    cover,
    tag_ids: JSON.stringify(label)
  });

  if (code === "200") {
    if (type === 1) {
      ElMessage.success("保存成功...,正在返回文章列表页");
    } else {
      ElMessage.success("增加成功...,正在返回文章列表页");
      setTimeout(() => {
        router.push({ name: "articleList" });
      }, 1000);
    }
  }
};

const onCancel = () => {
  state.flag = !state.flag;
};

const goHome = () => {
  router.push({ name: "articleList" });
};

const updateInfo = async (id: number) => {
  const res: any = await detailBlogApi({ id });
  if (res.code === "200" && res.data) {
    let { content, title, cover, desc, tag_ids, create_time } = res.data || {};
    state.value = content;
    state.title = title;

    updateData.value = {
      id,
      cover,
      desc,
      tag_ids,
      create_time
    };
  }
};

const fixBlogDetail = async (item: any, type: any) => {
  console.log(item);
  let { value, title, id } = state;
  let { desc, cover, label, publishTime } = item;
  const { data, code } = await updateBlogApi({
    id: id,
    title,
    desc,
    content: value,
    create_time: dayjs(publishTime).unix(),
    cover,
    tag_ids: JSON.stringify(label)
  });
  if (code === "200") {
    if (type === 1) {
      ElMessage.success("更新成功");
    } else {
      ElMessage.success("更新成功...,正在返回文章列表页");
      setTimeout(() => {
        router.push({ name: "articleList" });
      }, 1000);
    }
  }
};
</script>

<style lang="scss">
@mixin flex-auto($al: false, $jc: false, $row: row) {
  display: flex;
  flex-direction: $row;

  @if $al {
    align-items: $al;
  }

  @if $jc {
    justify-content: $jc;
  }
}
.admin {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  touch-action: none;
  .opts {
    height: 63px;
    padding: 0 40px;
    background-color: #ffffff;
    border: 0 1px 0 1px solid #e1e4e8;

    @include flex-auto(center, space-between);
    .left {
      flex: 1 1 auto;
      width: 70%;
      height: 100%;

      @include flex-auto(center);
      .custinput {
        box-sizing: border-box;
        width: 100%;
        font-size: 24px;
        font-weight: 500;
        color: #1d2129;
        border: none;
        outline: none;
      }
    }
    .right {
      flex: 1;

      @include flex-auto(center);

      align-items: center;
      .el-button {
        margin-right: 10px;
        border-radius: 0;
      }
      .el-avatar {
        margin-left: 20px;
      }
    }
  }
  .editos {
    .bytemd {
      height: calc(100vh - 63px) !important;
    }
  }
}
</style>
